package product;

import java.awt.EventQueue;

import javax.swing.JInternalFrame;
import javax.swing.JSeparator;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class CodeInput extends JInternalFrame {
	String Cnm;
	static Connection con;
	DefaultTableModel model;
	ProductMain5 ma;
	Vector<String> col = new Vector<String>();
	private JLabel lblNewLabel;
	private JSeparator separator;
	private JLabel lblNewLabel_1;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_3;
	private JTextField text1;
	private JTextField text2;
	private JTextField text3;
	private JTextField text4;
	private JTextField text5;
	private JButton btnNewButton;
	private JPanel panel;
	private JPanel panel_1;
	private JButton btnNewButton_1;
	private JComboBox comboBox;
	private JTextField text6;
	private JScrollPane scrollPane;
	private JTable table;
	private JComboBox comboBox_1;


	/**
	 * Create the frame.
	 */
	public CodeInput(Connection con, ProductMain5 m) {
		super("코드 생성",false,true,true,true);
		
		this.con = con;
		this.ma = m;
//		String a = ma.member;
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosed(InternalFrameEvent arg0) {
				ma.codeInput = null;
			}
		});
		col.add("거래처");
		col.add("사업자 번호");
		col.add("대표자");
		col.add("주소");
		col.add("전화번호");
		col.add("FAX");
		model = new DefaultTableModel(col, 0){
		public boolean isCellEditable(int rowIndex, int mColIndex) {
			return false;
		}
	};
		search();
		
		setBounds(100, 100, 931, 525);
		getContentPane().setLayout(null);
		getContentPane().add(getLblNewLabel());
		getContentPane().add(getSeparator());
		getContentPane().add(getLblNewLabel_1());
		getContentPane().add(getLabel());
		getContentPane().add(getLabel_1());
		getContentPane().add(getLabel_2());
		getContentPane().add(getLabel_3());
		getContentPane().add(getText1());
		getContentPane().add(getText2());
		getContentPane().add(getText3());
		getContentPane().add(getText4());
		getContentPane().add(getText5());
		getContentPane().add(getBtnNewButton());
		getContentPane().add(getPanel());
		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		table.getColumnModel().getColumn(0).setPreferredWidth(152);
		table.getColumnModel().getColumn(1).setPreferredWidth(80);
		table.getColumnModel().getColumn(2).setPreferredWidth(60);
		table.getColumnModel().getColumn(3).setPreferredWidth(100);
		table.getColumnModel().getColumn(4).setPreferredWidth(80);
		table.getColumnModel().getColumn(5).setPreferredWidth(80);
		
		DefaultTableCellRenderer Center = new DefaultTableCellRenderer();
		Center.setHorizontalAlignment(SwingConstants.CENTER);// 가운데 정렬
		TableColumnModel tcmSchedule = table.getColumnModel();
		tcmSchedule.getColumn(0).setCellRenderer(Center);
		tcmSchedule.getColumn(1).setCellRenderer(Center);
		tcmSchedule.getColumn(2).setCellRenderer(Center);
		tcmSchedule.getColumn(3).setCellRenderer(Center);
		tcmSchedule.getColumn(4).setCellRenderer(Center);
		tcmSchedule.getColumn(5).setCellRenderer(Center);
//		text4.setText(a);
		setMember();
		getContentPane().add(getComboBox_1());
	}
	
	public void setMember(){
		try{
			Statement stmt = con.createStatement();
			String sql = "select irum from memberdata where memberid = '"+ma.member+"'";
			
			ResultSet rs = stmt.executeQuery(sql);
			if(rs.next()){
			text4.setText(rs.getString("irum"));
			}
			rs.close();
			stmt.close();
		}catch(Exception a){
			a.printStackTrace();
		}
		
		
	}
	
	private boolean search() {
		try {
			model.setRowCount(0);
			Statement stmt = con.createStatement();
			String sql = "select name,num,ceo,address,phone,fax from customer order by num";
			ResultSet RS = stmt.executeQuery(sql);
			while (RS.next()) {
				Vector<String> row = new Vector<String>();
				row.add(RS.getString(1));
				row.add(RS.getString(2));
				row.add(RS.getString(3));
				row.add(RS.getString(4));
				row.add(RS.getString(5));
				row.add(RS.getString(6));
				model.addRow(row);
			}
			RS.close();
			stmt.close();

			return true;
		} catch (Exception e) {
			System.out.println("예외사항:" + e.getMessage());
			return false;
		}
	}
	
	public void search2() {
		String str = text6.getText();
		if(comboBox.getSelectedIndex() == 0){//사업자번호
			if(("").equals(str)){
				JOptionPane.showMessageDialog(null,"검색창에 입력된 값이 없습니다.");
			}
			else{
				
					try{
					model.setRowCount(0);
					String sql = "select name ,num, ceo, address, phone, fax from customer where num like '%"+str+"%' order by num";
					Statement ptm = con.createStatement();
					ResultSet rs = ptm.executeQuery(sql);
					while(rs.next()){
						Vector<String>aa = new Vector<String>();
						aa.add(rs.getString(1));
						aa.add(rs.getString(2));
						aa.add(rs.getString(3));
						aa.add(rs.getString(4));
						aa.add(rs.getString(5));
						aa.add(rs.getString(6));
						model.addRow(aa);
					}
					rs.close();
					ptm.close();
					
					
					if(model.getRowCount()==0){
						JOptionPane.showMessageDialog(null, "해당 정보가 없습니다. 검색창에 숫자를 입력해주세요.");
						
					}
					
					}catch(Exception ex){
						ex.printStackTrace();
						
					}
				}
			}
//			
		
			
		if(comboBox.getSelectedIndex() == 1){//회사명
			if(("").equals(str)){
				JOptionPane.showMessageDialog(null,"검색창에 입력된 값이 없습니다.");
			}else{
				try{
					
					model.setRowCount(0);
					String sql = "select name ,num,ceo,address,phone,fax from customer where name like '%"+str+"%' order by num";
					Statement ptm = con.createStatement();
					ResultSet rs = ptm.executeQuery(sql);
				while(rs.next()){
					Vector<String>aa = new Vector<String>();
					aa.add(rs.getString(1));
					aa.add(rs.getString(2));
					aa.add(rs.getString(3));
					aa.add(rs.getString(4));
					aa.add(rs.getString(5));
					aa.add(rs.getString(6));
					model.addRow(aa);
			}
			rs.close();
			ptm.close();
			
			if(model.getRowCount() == 0){
				JOptionPane.showMessageDialog(null, "해당 정보가 없습니다. 다시 입력해주세요.");
			}
			
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
			
	}
		if(comboBox.getSelectedIndex() == 2){//대표자
			if(("").equals(str)){
				JOptionPane.showMessageDialog(null,"검색창에 입력된 값이 없습니다.");
			}else{
				try{
					model.setRowCount(0);
					String sql = "select name ,num ,ceo ,address ,phone ,fax from customer where ceo like'%"+str+"%' order by num";
					Statement ptm = con.createStatement();
					ResultSet rs = ptm.executeQuery(sql);
					while(rs.next()){
						Vector<String> ceo = new Vector<String>();
						ceo.add(rs.getString(1));
						ceo.add(rs.getString(2));
						ceo.add(rs.getString(3));
						ceo.add(rs.getString(4));
						ceo.add(rs.getString(5));
						ceo.add(rs.getString(6));
						model.addRow(ceo);
					}
					rs.close();
					ptm.close();
					
					if(model.getRowCount() == 0){
						JOptionPane.showMessageDialog(null, "해당 정보가 없습니다. 다시 입력해주세요.");
					}
				}catch(Exception a){
					a.printStackTrace();
				}
			}
		}
		
		if(comboBox.getSelectedIndex() == 3){//주소
			if(("").equals(str)){
				JOptionPane.showMessageDialog(null,"검색창에 입력된 값이 없습니다.");
			}else{
				try{
					model.setRowCount(0);
					String sql = "select name ,num ,ceo ,address ,phone ,fax from customer where address like'%"+str+"%' order by num";
					Statement ptm = con.createStatement();
					ResultSet rs = ptm.executeQuery(sql);
					while(rs.next()){
						Vector<String> ceo = new Vector<String>();
						ceo.add(rs.getString(1));
						ceo.add(rs.getString(2));
						ceo.add(rs.getString(3));
						ceo.add(rs.getString(4));
						ceo.add(rs.getString(5));
						ceo.add(rs.getString(6));
						model.addRow(ceo);
					}
					rs.close();
					ptm.close();
					
					if(model.getRowCount() == 0){
						JOptionPane.showMessageDialog(null, "해당 정보가 없습니다. 다시 입력해주세요.");
					}
				}catch(Exception a){
					a.printStackTrace();
				}
			}
		}
	}
	
	public void input() {
		try{
			String code = text1.getText();
			String name = text2.getText();
			int price = Integer.parseInt(text3.getText());
			String customer = text5.getText();
			boolean tFlag = true;//아래의 예외문 처리가 끝나고 문제가 없으면 db저장 처리.
			
			if(code.equals("")){
				JOptionPane.showMessageDialog(null, "코드 값이 없습니다.");
				tFlag = false;
			}
			else if(name.equals("")){
				JOptionPane.showMessageDialog(null, "이름 값이 없습니다.");
				tFlag = false;
			}
			else if(customer.equals("")){
				JOptionPane.showMessageDialog(null, "거래처에 값이 없습니다.");
				tFlag = false;
				
			}else{
				if(tFlag){
					try{
						Statement stmt = con.createStatement();
						String sql = "insert into code values('" + code + "','" + name
								+ "'," + price + ",sysdate,'" + ma.member + "',sysdate,'" + ma.member
								+ "','" + Cnm + "')";
						 stmt.executeQuery(sql);
						 
							
						 stmt.close();
						 System.out.println("1");
							text1.setText("");
							text2.setText("");
							text3.setText("");
							text5.setText("");
				
							JOptionPane.showMessageDialog(null, "제품이 등록되었습니다.");
							
							
							
							
					}catch(Exception ev){
						ev.printStackTrace();
					}
				}
			}
			
		}catch(NumberFormatException a){
			JOptionPane.showMessageDialog(null, "가격에 값이 없거나 문자열이 들어가있습니다.");
			
		}
	}
	
	public void MouseC() {
		int idx = table.getSelectedRow();
		text5.setText(table.getValueAt(idx, 0) + "");
		Cnm = table.getValueAt(idx, 1) + "";
	}
	
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("코드 입력");
			lblNewLabel.setFont(new Font("굴림", Font.PLAIN, 29));
			lblNewLabel.setBounds(12, 10, 165, 30);
		}
		return lblNewLabel;
	}
	private JSeparator getSeparator() {
		if (separator == null) {
			separator = new JSeparator();
			separator.setBounds(12, 50, 205, 11);
		}
		return separator;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("제품 코드");
			lblNewLabel_1.setBounds(12, 76, 65, 21);
		}
		return lblNewLabel_1;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제품 이름");
			label.setBounds(12, 147, 77, 30);
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("제품 원가");
			label_1.setBounds(12, 203, 77, 30);
		}
		return label_1;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("받은 사람");
			label_2.setBounds(12, 262, 77, 30);
		}
		return label_2;
	}
	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("거래처");
			label_3.setBounds(12, 315, 77, 30);
		}
		return label_3;
	}
	private JTextField getText1() {
		if (text1 == null) {
			text1 = new JTextField();
			text1.setEditable(false);
			text1.setBounds(12, 107, 174, 21);
			text1.setColumns(10);
		}
		return text1;
	}
	private JTextField getText2() {
		if (text2 == null) {
			text2 = new JTextField();
			text2.setColumns(10);
			text2.setBounds(70, 152, 116, 21);
		}
		return text2;
	}
	private JTextField getText3() {
		if (text3 == null) {
			text3 = new JTextField();
			text3.setColumns(10);
			text3.setBounds(70, 208, 116, 21);
		}
		return text3;
	}
	private JTextField getText4() {
		if (text4 == null) {
			text4 = new JTextField();
			text4.setEditable(false);
			text4.setColumns(10);
			text4.setBounds(70, 267, 116, 21);
		}
		return text4;
	}
	private JTextField getText5() {
		if (text5 == null) {
			text5 = new JTextField();
			text5.setEditable(false);
			text5.setColumns(10);
			text5.setBounds(70, 320, 116, 21);
		}
		return text5;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("저장");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					input();
				}
			});
			btnNewButton.setBounds(36, 374, 138, 39);
		}
		return btnNewButton;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setBounds(247, 10, 669, 483);
			panel.setLayout(null);
			panel.add(getPanel_1());
			panel.add(getScrollPane());
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setBounds(0, 0, 669, 23);
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getBtnNewButton_1(), BorderLayout.EAST);
			panel_1.add(getComboBox(), BorderLayout.WEST);
			panel_1.add(getText6(), BorderLayout.CENTER);
		}
		return panel_1;
	}
	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("조회");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					search2();
				}
			});
		}
		return btnNewButton_1;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setModel(new DefaultComboBoxModel(new String[] {"사업자번호", "회사명", "대표자명", "주소"}));
		}
		return comboBox;
	}
	private JTextField getText6() {
		if (text6 == null) {
			text6 = new JTextField();
			text6.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent a) {
					if(a.getKeyCode() == KeyEvent.VK_ENTER){
						search2();
					}
				}
			});
			text6.setColumns(10);
		}
		return text6;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(0, 33, 657, 447);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable(model);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					MouseC();
				}
			});
		}
		return table;
	}
	private JComboBox getComboBox_1() {
		if (comboBox_1 == null) {
			comboBox_1 = new JComboBox();
			comboBox_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					selectCode();
				}
			});
			comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"종류", "전자제품", "조리도구", "생활용품", "문구", "의류", "청소도구"}));
			comboBox_1.setBounds(109, 76, 77, 21);
		}
		return comboBox_1;
	}
	
	public void selectCode(){
		try{
			String code = "";
			if(comboBox_1.getSelectedIndex()==1){//가전제품
				code = "A";
				//가전제품의 콤보박스를 클릭시 code에 A를 넣어서 아래의 sql에 있는 문에다 넣어서 검색을 처리하기 위해.
				//먼저 위에다 처리함. 이하 5개도 동일.
			}
			if(comboBox_1.getSelectedIndex()==2){//조리도구
				code = "B";
			}
			if(comboBox_1.getSelectedIndex()==3){//생활용품
				code = "C";
			}
			if(comboBox_1.getSelectedIndex()==4){//문방구
				code = "D";
			}
			if(comboBox_1.getSelectedIndex()==5){//의류
				code = "E";
			}
			if(comboBox_1.getSelectedIndex()==6){//청소도구
				code = "F";
			}
			
			
//구분선---------------------------------
//위에는 콤보박스 클릭 시 아래의 sql를 자동으로 검색하게 도와주는 코드입니다.
			
			String sql = "select to_char((select count (*) from code where pro_code like '%"+code+"%')+1,'000') as phj from dual";
			//to_char을 쓴 이유는 000형태를 고정하기 위해서 사용했습니다.
			PreparedStatement ptms = con.prepareStatement(sql);
			ResultSet rs = ptms.executeQuery();
			if(rs.next()){
				if(comboBox_1.getSelectedIndex() == 0){//종류
					text1.setText("");
				}
				
				if(comboBox_1.getSelectedIndex() == 1){//가전제품
					text1.setText("A"+rs.getString("phj").replace(" ", ""));
				}
				
				if(comboBox_1.getSelectedIndex() == 2){//조리도구
					text1.setText("B"+rs.getString("phj").replace(" ", ""));
				}
				
				if(comboBox_1.getSelectedIndex() == 3){//생활용품
					text1.setText("C"+rs.getString("phj").replace(" ", ""));
				}
				
				if(comboBox_1.getSelectedIndex() == 4){//문방구
					text1.setText("D"+rs.getString("phj").replace(" ", ""));
				}

				if(comboBox_1.getSelectedIndex() == 5){//의류
					text1.setText("E"+rs.getString("phj").replace(" ", ""));
				}

				if(comboBox_1.getSelectedIndex() == 6){//청소도구
					text1.setText("F"+rs.getString("phj").replace(" ", ""));
				}
				rs.close();
				ptms.close();
				
			}
			
			
		}catch(Exception a){
			a.printStackTrace();
		}
		
	}
}
